<template>
   <div>
     <el-button
       size="mini"
       @click="handleAdd()">添加</el-button>
     <el-table
       ref="multipleTable"
       :data="tableData"
       tooltip-effect="dark"
       style="width: 100%"
       @selection-change="handleSelectionChange">
       <el-table-column
         type="selection"
         width="55">
       </el-table-column>
       <el-table-column
         prop="productId"
         label="商品ID"
         width="120">
       </el-table-column>
       <el-table-column
         prop="skuCode"
         label="SKU编码"
       width="120">
       </el-table-column>
       <el-table-column
         prop="price"
         label="价格"
         width="120">
       </el-table-column>
       <el-table-column
         prop="stock"
         label="库存"
         width="120">
       </el-table-column>
       <el-table-column
         prop="lowStock"
         label="预警库存"
         width="120">
       </el-table-column>
       <el-table-column
         prop="spData"
         label="商品销售属性"
         width="120">
       </el-table-column>
       <el-table-column
         prop="pic"
         label="展示图片"
         width="120">
       </el-table-column>
       <el-table-column
         prop="sale"
         label="销量"
         width="120">
       </el-table-column>
       <el-table-column
         prop="promotionPrice"
         label="单品促销价格"
         width="120">
       </el-table-column>
       <el-table-column
         prop="lockStock"
         label="锁定库存"
         width="120">
       </el-table-column>

       <el-table-column prop="pic" label="商品图片">
         <template slot-scope="scope">
           <el-image :src="scope.row.pic" style="width: 50px"></el-image>
         </template>
       </el-table-column>

       <el-table-column label="操作">
         <template slot-scope="scope">
           <el-button
             size="mini"
             @click="handleEdit(scope.row)">修改</el-button>
           <el-button
             size="mini"
             type="danger"
             @click="handleDelete(scope.$index,scope.row)">删除</el-button>
         </template>
       </el-table-column>


     </el-table>
     <div class="block">
       <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="page.current"
         :page-sizes="[3, 6, 9, 12]"
         :page-size="page.size"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
       </el-pagination>
     </div>



     <div>
       <!-- 添加或修改商品对话框 -->
       <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
         <el-form ref="form" :model="form" :rules="rules" label-width="80px">
           <el-form-item label="sku编码" prop="name">
             <el-input v-model="form.skuCode" placeholder="请输入商品名称" />
           </el-form-item>
           <el-form-item label="价格" prop="price">
             <el-input v-model="form.price" placeholder="请输入商品价格" />
           </el-form-item>
           <el-form-item label="库存" prop="promotionPrice">
             <el-input v-model="form.promotionPrice" placeholder="请输入促销价格" />
           </el-form-item>
           <el-form-item label="预警库存" prop="subTitle">
             <el-input v-model="form.lowStock" placeholder="请输入副标题" />
           </el-form-item>
           <el-form-item label="商品促销属性" prop="description">
             <el-input v-model="form.spData" placeholder="请输入商品描述" />
           </el-form-item>

           <el-upload
               class="avatar-uploader"
               action="http://localhost:8080/generator/pmsskustock/uploadImg"
               :show-file-list="false"
               :headers="myToken"
               :on-success="handleAvatarSuccess"
               :before-upload="beforeAvatarUpload">
               <img v-if="imageUrl" :src="imageUrl" class="avatar">
               <i v-else class="el-icon-plus avatar-uploader-icon"></i>
           </el-upload>

         </el-form>
         <div slot="footer" class="dialog-footer">
           <el-button type="primary" @click="submitForm">确 定</el-button>
           <el-button @click="cancel">取 消</el-button>
         </div>
       </el-dialog>

     </div>
   </div>


</template>
<script>
import {fetchList, getObj, addObj, putObj, delObj} from '@/api/stock/pmsskustock'
import {tableOption} from '@/const/crud/stock/pmsskustock'
import {mapGetters} from 'vuex'
import store from "@/store";
export default {
  data() {
    return {
      myToken:{
        Authorization : 'Bearer ' +store.getters.access_token
      },
      imageUrl:'',
      tableData: [],
      multipleSelection: [],
      total: 0,
      page:{
        current:1,
        size:3
      },
      title:"",
      open:false,
      form:{},
      //表单验证
      rules: {
        skuCode: [
          { required: true, message: "SKU编码不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        stock: [
          { required: true, message: "库存不能为空", trigger: "blur" }
        ],
        lowStock: [
          { required: true, message: "预警库存不能为空", trigger: "blur" }
        ],
        spData: [
          { required: true, message: "商品销售属性不能为空", trigger: "blur" }
        ],
        pic: [
          { required: true, message: "图片不能为空", trigger: "blur" }
        ],
        sale: [
          { required: true, message: "销量不能为空", trigger: "blur" }
        ],
        promotionPrice: [
          { required: true, message: "单品促销价格不能为空", trigger: "blur" }
        ],
        lockStock: [
          { required: true, message: "锁定库存不能为空", trigger: "blur" }
        ]
      }

    }
  },

  methods: {


    //图片上传
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.pic=file.response.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            putObj(this.form).then(response => {
              this.$message.success('修改成功')
              this.open = false;
              this.getList();
            });
          } else {
            addObj(this.form).then(response => {
              this.$message.success('添加成功')
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        price: null,
        subTitle:null,
        promotionPrice: null,
        description: null,
        pic:null,
      };

    },
    //添加
    handleAdd(){
      this.reset();
      this.open=true;
      this.title="添加商品"
    },
    //删除
    handleDelete(index,row) {
      console.log(index);
      this.$confirm('是否确认删除ID为' + row.id, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    //修改
    handleEdit(row) {
      this.reset();
      console.log(row.id)
      //this.form=response.data;
      this.form=row
      this.open=true;
      this.title="修改商品"
      this.imageUrl=row.pic
      this.getList()
    },
    //列表
    getList() {
      fetchList(this.page,this.tableData).then(response => {
        this.tableData = response.data.data.records
        this.total = response.data.data.total
      })
    },
    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page.size=val
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page.current=val
      this.getList();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  },
  created() {
    this.getList();
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
